import api from '../../../api/index';
import Dialog from '@vant/weapp/dialog/dialog';
import uploadOss from '../../../utils/uploadFileOss/index'
Page({
	/**
   * 页面的初始数据
   */
	data: {
		showEvaluate: false,
		evaluatesData: {},
		evaluateForm: {
			comment: '',
			id: '',
			images: '',
			stars: 0
		},
		tab: [
			{ name: '全部', state: '' },
			{ name: '待付款', state: ['new', '待付款'] },
			{ name: '待发货', state: ['paied', '待发货'] },
			{ name: '待收货', state: ['shipped', '待收货'] },
			{ name: '退款/售后', state: ['RR', '退货退款'] },
			{ name: '待评价', state: ['completed', '已完成'] }
		],
		active: 0,
		showshoporderlist: false,
		showunevaluate: false,
		shoporderlist: [],
		unevaluate: [],
		showshop: false,
		cancelPayList: null,
		saveActive: '',
		radio: [],
		fileList: [],
		evaluateFileList: [],
		refundtype: 'RO',
		refundreason: '',
		dizhidata: [],
		checkedAddress: {},
		show: false,
		radio: null,
	},
	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		this.deliveraddressList()
		const { type, index } = options
		console.log(type, '请求接口')
		if (type == 'all') {
			this.shoporderlist('', index);
		} else if (index == 5) {
			this.setData({
				active: parseInt(index)
			});
			this.unevaluate();
		} else if (index == 4) {
			this.setData({
				active: parseInt(index)
			});
			this.unpay();
		} else {
			this.setData({
				active: parseInt(index)
			});
			this.shoporderlist(type.split(","), index);
		}
	},
	inpuStar(e) {
		this.setData({
			'evaluateForm.stars': e.detail
		})
	},
	async goEvaluate(e) {
		const goodsid = e.target.dataset.goodsid
		const id = e.target.dataset.id
		const actions = {
			data: {
				goodsid: goodsid
			}
		}
		// goodsimages
		try {
			const res = await api.post('/api/hxhealth/shoporder/unevaluate', actions);
			console.log('=======商品评价==============');
			console.log(res);
			if (res && res.length > 0) {
				res?.forEach(item => {
					item.goodsTotal = this.getEvaluateTotal(item)
				})
				this.setData({
					evaluatesData: res,
					evaluateForm: {
						comment: '',
						id: id,
						images: '',
						stars: 0
					}
				})
				console.log(this.data.evaluatesData);
				this.setData({
					showEvaluate: true
				})
			}
		} catch (e) {
			console.log('loadDesic->', e);
			return null;
		}
	},
	async saveEvaluate() {
		try {
			const form = this.data.evaluateForm
			if (!form.comment) {
				wx.showToast({
					title: '请填写评价内容',
					icon: 'none',
				})
				return
			}
			if (form.stars < 1) {
				wx.showToast({
					title: '星级评价不能小于1',
					icon: 'none',
				})
				return
			}
			const imgList = []
			this.data.evaluateFileList.forEach(item => {
				const obj = {
					file: item.url[0]
				}
				imgList.push(obj)
			})
			const actions = {
				data: [{
					id: form.id,
					// images: JSON.stringify(this.data.evaluateFileList),
					images: {
						images: imgList
					},
					comment: form.comment,
					stars: form.stars
				}]
			}
			const res = await api.post('/api/hxhealth/shoporder/evaluate', actions);
			console.log('save after=', res);
			if (res) {
				wx.showToast({
					title: '评价成功',
					icon: 'none',
				})
				this.setData({
					showEvaluate: false
				})
			}
		} catch (e) {
			console.log('loadDesic->', e);
			if (Array.isArray(e?.body) && e.body.length) {
				const val = Object.values(e.body[0])
				wx.showToast({
					title: val,
					icon: 'none',
				})
			}
			return null;
		}
	},
	getEvaluateTotal(i) {
		const price = parseFloat(i.goodsprice)
		const num = parseFloat(i.goodsamount)
		return (price * num).toFixed(2)
	},
	// 订单收货列表
	shoporderlist(type, index) {
		console.log(type);
		console.log(index);
		this.setData({
			active: index
		});
		const actions = {
			data: {
				state: type ? type : ''
			}
		};
		try {
			api.post('/api/hxhealth/shoporder/list', actions).then((res) => {
				// console.log(res);
				console.log('----res----', res);
				if(res.length > 0) {
					for (let i = 0; i < res.length; i++) {
						if (res[i].items.length > 0) {
							for (var j = 0; j < res[i].items.length; j++) {
								let totalPrice = 0
								const element = res[i].items;
								// console.log(element);
								for (let y = 0; y < element.length; y++) {
									if (element[y].goodsid && element[y].goodsid.length > 0) {
										res[i].goodsName = element[y].goodsid[1]
										res[i].goodsid = element[y].goodsid[0]
									}
									totalPrice = totalPrice + Number(element[y].sums)
									var images = element[y].goodsimages;
									// console.log(images);
									// 判断是否为数组转换的字符串
									if (images.startsWith('[')) {
										// 是数组转换的字符串，进行处理
										// console.log('第一种情况：数组转换的字符串', i, images);
										var imagesArray = JSON.parse(images);
										var firstImageUrl = imagesArray[0].file;
										// console.log("第一种情况：数组转换的字符串");
										// console.log('第一个图片链接：' + firstImageUrl);
										res[i].items[y].firstImageUrl = firstImageUrl;
									} else {
										// console.log('第二种情况：逗号隔开的图片地址');
										// 是逗号隔开的图片地址，进行处理
										var imageUrls = images.split(',');
										// console.log(imageUrls);
										var firstImageUrl = imageUrls[0];
										// console.log('第一个图片链接：' + firstImageUrl);
										res[i].items[y].firstImageUrl = firstImageUrl;
									}
								}
								res[i].totalPrice = totalPrice
							}
							wx.hideLoading()
							this.setData({
								shoporderlist: res,
								showshoporderlist: true,
								showunevaluate: false
							});
						} else {
							console.log('空---------');
						}
					} 
				} else {
					console.log('列表是空');
					this.setData({
						shoporderlist: [],
						showshoporderlist: true,
						showunevaluate: false
					});
				}
				
				console.log(res);
				
			});
		} catch (e) {
			console.error(e);
		}
	},
	// 获取收货地址列表
	async deliveraddressList() {
		console.log('deliveraddressList')
		const actions = {
			data: {
				name: '',
			}
		}
		try {
			const res = await api.post('/api/hxhealth/deliveraddress/list', actions);
			// this.setData({
			// 	radio: 0
			// })
			if (res && res.length > 0) {
				const reRes = res.reverse()
				// reRes.forEach((item, index) => {
				// 	if (item.defau == '1') {
				// 		this.setData({
				// 			radio: index
				// 		})
				// 		return
				// 	}
				// })
				this.setData({
					dizhidata: reRes
				});
				this.setData({
					checkedAddress: this.data.dizhidata[this.data.radio],
				});
			} else {
				this.setData({
					dizhidata: []
				});
				this.setData({
					checkedAddress: {},
				});
			}
		} catch (e) {
			console.log('deliveraddressList->', e);
			return null;
		}
	},
	onClickButton() {
		this.setData({
			showshop: false
		})
	},
	//文件选择
	afterRead(event) {
		const fileprop = event.target.dataset.fileprop
		const { file } = event.detail;
		console.log(file);
		var num = []
		num.push(file.url)
		console.log(num);
		console.log(num);
		this.uploadDIY(
			num,
			0,
			0,
			0,
			num.length,
			num,
			fileprop
		)
	},
	/* 删除图片*/
	deleteImg(e) {
		const fileprop = e.target.dataset.fileprop
		let fileList = this.data[fileprop];
		fileList.splice(e.detail.index, 1);
		this.setData({ [fileprop]: fileList });
	},
	uploadDIY(filePaths, successUp, failUp, i, length, param, fileprop) {
		// 正在上传
		param.doing = true // this.data.prove.doing = true;
		param.imagesUrl = []
		let that = this
		// wx.showLoading({
		//     title: `上传${i}/${length}张图片中`,
		//     duration: 1000
		// })

		uploadOss(filePaths[i])
			.then((res) => {
				successUp++
				i++
				param.imagesUrl.push(res.url)
				if (i === length) {
					// 全部上传成功
					console.log('图片上传成功后的url', param.imagesUrl, length)
					if (successUp === length) {
						param.uploadSuccess = true
						console.log('图片上传成功进入回调')
						let img = {
							url: param.imagesUrl,
							name: '图片1',
						}
						let fileList = this.data.fileList;
						fileList.push(img);
						this.setData({ [fileprop]: fileList });
						// wx.hideLoading()
						// that.savetmp(param.imagesUrl[0])
					} else {
						// 图片上传部分失败
						param.doing = false
						wx.hideLoading()
						wx.showToast({
							title: '上传图片失败,请重新上传！',
							icon: 'none',
							duration: 2000
						})
					}
				} else {
					// 递归调用uploadDIY函数
					that.uploadDIY(
						filePaths,
						successUp,
						failUp,
						i,
						length,
						param,
						fileprop
					)
				}
			})
			.catch((e) => {
				console.log('---图片上传失败 catch--- e', e)
				param.doing = false
				failUp++
				wx.hideLoading()
				wx.showToast({
					title: '图片上传失败，请重新上传！',
					icon: 'none',
					duration: 2000
				})
			})
	},
	unevaluate() {
		wx.showLoading({
			title: '加载中',
		})
		// /api/hxhealth/shoporder/unevaluate
		const actions = {
			data: {}
		};
		try {
			api.post('/api/hxhealth/shoporder/unevaluate', actions).then((res) => {
				// console.log(res);
				console.log('----res----', res);
				console.log(res);
				for (let i = 0; i < res.length; i++) {
					if (res[i].goodsimages) {
						let images = res[i].goodsimages;
						// console.log(images);
						// 判断是否为数组转换的字符串
						if (images.startsWith('[')) {
							// 是数组转换的字符串，进行处理
							// console.log('第一种情况：数组转换的字符串', i, images);
							var imagesArray = JSON.parse(images);
							var firstImageUrl = imagesArray[0].file;
							// console.log("第一种情况：数组转换的字符串");
							// console.log('第一个图片链接：' + firstImageUrl);
							res[i].firstImageUrl = firstImageUrl;
						} else {
							// console.log('第二种情况：逗号隔开的图片地址');
							// 是逗号隔开的图片地址，进行处理
							var imageUrls = images.split(',');
							// console.log(imageUrls);
							var firstImageUrl = imageUrls[0];
							// console.log('第一个图片链接：' + firstImageUrl);
							res[i].firstImageUrl = firstImageUrl;
						}
					}
				}
				console.log(res);
				wx.hideLoading()
				this.setData({
					unevaluate: res,
					showshoporderlist: false,
					showunevaluate: true
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	unpay(type) {
		// this.setData({
		// 	active: index
		// });
		const actions = {
			data: {
				state: type ? type : ''
			}
		};
		try {
			api.post('/api/hxhealth/shoporder/refundlist').then((res) => {
				// console.log(res);
				console.log('----res----', res);
				for (let i = 0; i < res.length; i++) {
					if (res[i].goodsimages) {
						let images = res[i].goodsimages;
						// console.log(images);
						// 判断是否为数组转换的字符串
						if (images.startsWith('[')) {
							// 是数组转换的字符串，进行处理
							// console.log('第一种情况：数组转换的字符串', i, images);
							var imagesArray = JSON.parse(images);
							var firstImageUrl = imagesArray[0].file;
							// console.log("第一种情况：数组转换的字符串");
							// console.log('第一个图片链接：' + firstImageUrl);
							res[i].firstImageUrl = firstImageUrl;
						} else {
							// console.log('第二种情况：逗号隔开的图片地址');
							// 是逗号隔开的图片地址，进行处理
							var imageUrls = images.split(',');
							// console.log(imageUrls);
							var firstImageUrl = imageUrls[0];
							// console.log('第一个图片链接：' + firstImageUrl);
							res[i].firstImageUrl = firstImageUrl;
						}
					}
				}
				console.log(res);
				wx.hideLoading()
				this.setData({
					unevaluate: res,
					showshoporderlist: false,
					showunevaluate: true
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	onChangeTab(event) {
		console.log('onChangeTab', event)
		this.setData({
			saveActive: this.data.tab[event.detail.name].state
		})
		if (event.detail.name == 5) {
			this.unevaluate();
		} else if (event.detail.name == 4) {
			var state = this.data.tab[event.detail.name].state;
			this.unpay(state);
		} else {
			var state = this.data.tab[event.detail.name].state;
			this.shoporderlist(state);
		}
		this.setData({
			active: event.detail.name
		});

		// wx.showToast({
		// 	title: `切换到标签 ${event.detail.name}`,
		// 	icon: 'none'
		// });
	},
	wxpay(e) {
		console.log(e.target.dataset.code);
		// let openid = wx.getStorageSync('openid')
		let orderid = e.target.dataset.code
		// 必须提供appId,userOrg,orderId,openId
		const actions = {
			data: {
				appId: 'wxeed56b13879c5337',
				userOrg: 'hongxing',
				// openid,
				orderid
			}
		}
		api.post('/api/hxhealth/shoporder/wxpay', actions).then((res) => {
			console.log(res);
			this.wxrequestPayment(res[0], orderid)
			// wx.showToast({
			// 	title: '支付',
			// 	icon: 'none',
			// 	duration: 3000
			// });
		});
	},
	wxrequestPayment(result, orderid) {
		console.log(orderid);
		var that = this
		that.setData({
			result
		});
		wx.requestPayment({
			timeStamp: result.timeStamp,
			nonceStr: result.nonceStr,
			package: 'prepay_id=' + result.prepayId,
			signType: 'MD5',
			paySign: result.paySign,
			success(res) {
				console.log(res);
				console.log('支付 完成');
				wx.redirectTo({
					url: `/shop/pages/myordersuccess/index?orderid=${orderid}`
				})
			},
			fail(res) {
				console.log(res);
				console.log('支付失败');
				Dialog.confirm({
					cancelButtonTrext: '放弃',
					confirmButtonText: '继续付款',
					cancelButtonColor: 'dimgrey',
					confirmButtonColor: 'dodgerblue',
					message: '确认要放弃付款吗？',
				}).then(() => {
					console.log('1111');
					// console.log(this);
					// var that = this
					// that.wxpay(that.data.orderid)
				})
					.catch(() => {
						console.log('2222');
					});
			}
		})
	},
	changerefundtype(e) {
		this.setData({
			refundtype: e.target.dataset.index
		})
	},
	// 取消付款
	cancelPay(e) {
		console.log(e.target.dataset.index);
		var index = e.target.dataset.index
		console.log(this.data.shoporderlist[index]);
		this.setData({
			cancelPayList: this.data.shoporderlist[index],
			showshop: true
		});
	},
	// 取消订单
	cancelRemovePay(e) {
		console.log(e.target.dataset);
		var code = e.target.dataset.code
		var active = e.target.dataset.active
		  Dialog.confirm({
			title: '取消订单',
			message: '确定要取消此订单吗？',
		  })
			.then(() => {
			  api.get(`/api/hxhealth/shoporder/remove/${code}`).then((res) => {
				console.log(res);
				wx.showToast({
					title: '取消成功',
					icon: 'none',
				})
		if(active == 0) {
			this.shoporderlist()
		} else if (active == 1) {
			this.shoporderlist(["new", "待付款"])
		}
			}).catch(e => {
				wx.showToast({
					icon: 'error',
					duration: 1200,
					title: e.faultstring,
				})
			});
			})
			.catch(() => {
				console.log('不取消');
			});
		
	},
	goOrderid(e) {
		console.log(e.target.dataset.id);
		let id = e.target.dataset.id
		wx.navigateTo({ url: `/shop/pages/detail/index?id=${id}` });
	},

	onCloseShop() {
		this.setData({ showshop: false });
	},
	onCloseEvaluate() {
		this.setData({ showEvaluate: false });
	},
	onChange(event) {
		this.setData({
			radio: event.detail,
		});
	},
	// 确认收货
	confirmReceipt(e) {
		console.log(e, 'AAAAAAAAAAA')
		api.get(`/api/hxhealth/shoporder/confirm/${e.target.dataset.id}`).then((res) => {
			console.log(res);
			wx.showToast({
				title: '确认收货成功',
				icon: 'none',
			})
			this.shoporderlist(this.data.saveActive)
		}).catch(e => {
			wx.showToast({
				icon: 'error',
				duration: 1200,
				title: e.faultstring,
			})
		});
	},
	inputrefundreason(e) {
		this.setData({
			refundreason: e.detail.value
		})
	},
	inputEvaluateComment(e) {
		this.setData({
			'evaluateForm.comment': e.detail.value
		})
	},
	//   提交退款申请
	onClickRefund(e) {
		console.log(this.data.radio);
		if (this.data.radio.length === 0) {
			wx.showToast({
				title: '请选择要退款的商品',
				icon: 'none',
			})
			return
		}
		if (!this.data.refundreason) {
			wx.showToast({
				title: '请输入退款原因',
				icon: 'none',
			})
			return
		}
		const idList = []
		this.data.radio.forEach(item => {
			idList.push(this.data.cancelPayList.items[item].id)
		})
		console.log(idList, 'idList')
		const actions = {
			data: [{
				id: idList.join(','),
				refundimages: JSON.stringify(this.data.fileList),
				refundreason: this.data.refundreason,
				refundtype: this.data.refundtype,
			}]
		}
		api.post('/api/hxhealth/shoporder/refund', actions).then((res) => {
			wx.showToast({
				title: '已申请退款！',
				icon: 'none',
			})
			this.setData({
				showshop: false
			})
			this.shoporderlist(this.data.saveActive)
		}).catch(e => {
			wx.showToast({
				icon: 'error',
				duration: 1200,
				title: e.faultstring,
			})
		});
	},
	showPopup(e) {
		console.log(e.currentTarget.dataset.item);
		this.setData({
			goChangeAdressitem: e.currentTarget.dataset.item,
			show: true
		});
	},
	onChangeTrue(event) {
		console.log(event);
		this.setData({
			radio: event.detail,
		});
		console.log(event.detail);
	},
	// 订单更改地址
	gochangeaddr(address,addressregion,id,mobile,receiver) {
		const actions = {
			data: [{
				address,addressregion,id,mobile,receiver
			}]
		}
		api.post('/api/hxhealth/shoporder/changeaddr', actions).then((res) => {
			wx.showToast({
				title: '更改成功',
				icon: 'none',
			})
			this.setData({
				radio: ''
			});
		}).catch(e => {
			wx.showToast({
				icon: 'error',
				duration: 1200,
				title: e.faultstring,
			})
		});
	},
	goChangeAdress() {
		wx.navigateTo({ url: '/shop/pages/deliveraddress/index' });
	},
	onClose() {
		this.setData({ show: false });
	},
	onTrue() {
		console.log(this.data.radio);
		console.log(this.data.dizhidata[this.data.radio]);
		console.log(this.data.goChangeAdressitem);
		let changeadressreult = this.data.dizhidata[this.data.radio]
		let payId = this.data.goChangeAdressitem
		this.gochangeaddr(changeadressreult.address,changeadressreult.addressregion,payId.id,changeadressreult.mobile,changeadressreult.receiver)
		this.onClose()
	},
	deleteRecord(e) {
		console.log(e);
		let id = e.currentTarget.dataset.id
		Dialog.confirm({
			title: '取消记录',
			message: '确定要删除此订单吗？',
		  })
			.then(() => {
			  api.get(`/api/hxhealth/shoporder/refundrem/${id}`).then((res) => {
				console.log(res);
				wx.showToast({
					title: '删除成功',
					icon: 'none',
				})
				this.unpay()
			}).catch(e => {
				wx.showToast({
					icon: 'error',
					duration: 1200,
					title: e.faultstring,
				})
			});
			})
			.catch(() => {
				console.log('不取消');
			});
	},
	// 点击复制
	copyBtn(e){
		console.log(e);
		console.log('fuzhifuzhi ');
		let content = e.currentTarget.dataset.logno
		console.log(content);
			// let that = this;
			wx.setClipboardData({//复制文本
				data: content,
				 success: function (res) {
					   wx.showToast({
						 title: '复制成功',
						icon:"none",
						mask:"true"//是否设置点击蒙版，防止点击穿透
					  })
				}
			 })
	 },
	 urgeProgress() {
		wx.showToast({
			title: '已催促商家',
		   icon:"none",
		   mask:"true"//是否设置点击蒙版，防止点击穿透
		 })
	 },
	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady() { },

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() { },

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() { },

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() { },

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() { },

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() { },

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() { }
});
